package com.webex.ta.hydra.gui.menu;

import com.webex.ta.hydra.core.PropertyManager;

import javax.swing.*;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import java.util.StringTokenizer;

/**
 * Created by Cisco WebEx.
 * User: vegaz
 * Date: 2010-9-30
 * Time: 12:27:42
 */
public class DynamicMenu extends JMenu implements MenuListener {
    protected DynamicMenuProvider provider;

    private int fixedSize;

    public DynamicMenu(String name, String label) {
        if (label == null)
            label = name;
        addMenuListener(this);
        setText(label);

        String menuItems = PropertyManager.getInstance().getProperty(name);
        if (menuItems != null) {
            StringTokenizer st = new StringTokenizer(menuItems);
            while (st.hasMoreTokens()) {
                String menuItemName = st.nextToken();
                if (menuItemName.equals("-"))
                    addSeparator();
                else
                    add(DynamicMenuFactory.loadMenuItem(menuItemName, true));
            }
        }

        fixedSize = getMenuComponentCount();
    }

    public void update() {
        while (getMenuComponentCount() != fixedSize)
            remove(getMenuComponentCount() - 1);

        if (provider != null)
            provider.update(this);
    }

    public void setProvider(DynamicMenuProvider provider) {
        this.provider = provider;
    }

    public void menuCanceled(MenuEvent e) {
    }

    public void menuSelected(MenuEvent e) {
        update();
    }

    public void menuDeselected(MenuEvent e) {
    }
}
